package com.holyn.guofang.view.distinguish;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.ImagePartitionWo;
import com.holyn.guofang.model.webhttp.wo.ImageWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.brand.BrandContract;
import com.holyn.guofang.presenter.brand.BrandPresenter;
import com.holyn.guofang.presenter.distinguish.DistinguishContract;
import com.holyn.guofang.presenter.distinguish.DistinguishPresenter;
import com.holyn.guofang.view.BaseActivity;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/7/25.
 */

public class ImgPartitionActivity extends BaseActivity implements BaseView, BrandContract.ImgPartitionView, DistinguishContract.UploadView{

    private static final int REQUEST_ACTION_UPLOAD_IMAGE = 0x0001;
    private static final int REQUEST_ACTION_POST_IMG_PARTITION = 0x0002;

    private static final int REQUEST_CODE_GO_PREVIEW = 0x0001;

    @BindView(R.id.imageview)
    ImageView imageview;
    @BindView(R.id.rv_image_colors)
    RecyclerView rvImageColors;
    @BindView(R.id.tv_group)
    TextView tvGroup;
    @BindView(R.id.btn_partition)
    Button btnPartition;
    @BindView(R.id.btn_reset)
    Button btnReset;
    @BindView(R.id.btn_partition_preview)
    Button btnPartitionPreview;

    private String imagePath;
    private String SrcImgID;

    private DistinguishContract.Presenter disPresenter;
    private BrandContract.Presenter brandPresenter;

    private ImagePartitionWo imagePartitionWo;
    private MyRecyclerAdapter colorRecyclerAdapter;

    private List<String> selectGroupList = new ArrayList<>();
    private String mainImageUrl = "";

    public static void startForResult(Activity fromActivity, String imagePath, String SrcImgID, String mainImageUrl, int requestCode){
        Intent intent = new Intent(fromActivity, ImgPartitionActivity.class);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_IMAGE_PATH, imagePath);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID, SrcImgID);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL, mainImageUrl);
        fromActivity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_img_partition;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("图像分拆组合");
        initData();
    }

    private void initData(){
        imagePath = getIntent().getStringExtra(SeniorDistinguishActivity.INTENT_KEY_IMAGE_PATH);
        SrcImgID = getIntent().getStringExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID);
        mainImageUrl = getIntent().getStringExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL);

        disPresenter = new DistinguishPresenter(this);
        disPresenter.addUploadViewListener(this);
        brandPresenter = new BrandPresenter(this);
        brandPresenter.addImgPartitionView(this);

        if (TextUtils.isEmpty(SrcImgID)){
            disPresenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
        } else {
            brandPresenter.postImgPartition(REQUEST_ACTION_POST_IMG_PARTITION, SrcImgID);
        }
    }

    @OnClick({R.id.btn_partition, R.id.btn_reset, R.id.btn_partition_preview})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_partition:
                String result = colorRecyclerAdapter.getSelectGroup();
                if (TextUtils.isEmpty(result)){
                    toastMsg("请点击颜色方块选择组合");
                } else {
                    selectGroupList.add(result);
                    String text = "";
                    for (int i = 0; i<selectGroupList.size(); i++){
                        if (i == 0){
                            text = text+"组合"+(i+1)+ ": "+selectGroupList.get(i);
                        } else {
                            text = text+"\n组合"+(i+1)+ ": "+selectGroupList.get(i);
                        }
                    }
                    tvGroup.setText(text);
                }
                break;
            case R.id.btn_reset:
                tvGroup.setText("请选择需要的分拆组合");
                selectGroupList.clear();
                break;
            case R.id.btn_partition_preview:
                if (selectGroupList.size() > 0){
                    String groupNum = "";
                    for (String selectGroup: selectGroupList){
                        if (TextUtils.isEmpty(groupNum)){
                            groupNum = groupNum + selectGroup;
                        } else {
                            groupNum = groupNum + "|" + selectGroup;
                        }
                    }

                    ArrayList<String> defaultSonImgLIst = new ArrayList<>();
                    List<ImagePartitionWo.DataBean.DefimageBean> defimageBeanList = imagePartitionWo.getData().getDefimage();
                    for (ImagePartitionWo.DataBean.DefimageBean defimageBean: defimageBeanList){
                        defaultSonImgLIst.add(defimageBean.getDefImageUrl());
                    }

                    ImgPartitionPreviewActivity.startForResult(ImgPartitionActivity.this, SrcImgID, mainImageUrl, groupNum, defaultSonImgLIst, REQUEST_CODE_GO_PREVIEW);

                } else {
                    toastMsg("请选择需要的分拆组合");
                }
                break;
        }
    }

    @Override
    public void requestStart(Integer requestAction) {
        showLoadingDialog();
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        closeLoadingDialog();
        toastMsg("出现异常");
    }

    @Override
    public void requestComplete(Integer requestAction) {

    }

    @Override
    public void responseSuccess(int requestAction, ImagePartitionWo imagePartitionWo) {
        if (imagePartitionWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            this.imagePartitionWo = imagePartitionWo;
            colorRecyclerAdapter = new MyRecyclerAdapter(imagePartitionWo.getData().getColor());
            rvImageColors.setLayoutManager(new GridLayoutManager(ImgPartitionActivity.this, 6));
            rvImageColors.addItemDecoration(new GridSpacingItemDecoration(6,20,false));
            rvImageColors.setAdapter(colorRecyclerAdapter);

            Glide.with(ImgPartitionActivity.this).load(imagePartitionWo.getData().getUrl())
//                    .error(R.drawable.ic_empty_image)
                    .into(imageview);

//            ArrayList<String> defaultSonImgLIst = new ArrayList<>();
//            List<ImagePartitionWo.DataBean.DefimageBean> defimageBeanList = imagePartitionWo.getData().getDefimage();
//            for (ImagePartitionWo.DataBean.DefimageBean defimageBean: defimageBeanList){
//                defaultSonImgLIst.add(defimageBean.getDefImageUrl());
//            }
//            Intent intent = getIntent();
//            intent.putStringArrayListExtra(ImgPartitionPreviewActivity.INTENT_KEY_SELECT_SON_IMAGE_LIST, defaultSonImgLIst);
//            setResult(Activity.RESULT_OK, intent);

        }
        closeLoadingDialog();
    }

    @Override
    public void responseSuccess(Integer requestAction, ImageWo imageWo) {
        if (imageWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            SrcImgID = imageWo.getSrcImgID();
            mainImageUrl = imageWo.getUrl();
            brandPresenter.postImgPartition(REQUEST_ACTION_POST_IMG_PARTITION, SrcImgID);
        } else {
            closeLoadingDialog();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK){
            switch (requestCode){
                case  REQUEST_CODE_GO_PREVIEW://返回选中子图
                    ArrayList<String> selectSonImgUrlList = data.getStringArrayListExtra(ImgPartitionPreviewActivity.INTENT_KEY_SELECT_SON_IMAGE_LIST);
                    Intent intent = getIntent();
                    intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID, SrcImgID);
                    intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL, mainImageUrl);
                    intent.putStringArrayListExtra(ImgPartitionPreviewActivity.INTENT_KEY_SELECT_SON_IMAGE_LIST, selectSonImgUrlList);
                    setResult(Activity.RESULT_OK, intent);
                    ImgPartitionActivity.this.finish();
                    break;
            }
        }
    }

    private class MyRecyclerAdapter extends BaseQuickAdapter<ImagePartitionWo.DataBean.ColorBean, BaseViewHolder>{

        private boolean isOnBind = false;
        private List<Boolean> isCheckList = new ArrayList<>();

        public MyRecyclerAdapter(@Nullable List<ImagePartitionWo.DataBean.ColorBean> data) {
            super(R.layout.item_color, data);
            for (int i = 0; i<data.size(); i++){
                isCheckList.add(false);
            }
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, ImagePartitionWo.DataBean.ColorBean colorBean) {
            isOnBind = true;
            CheckBox cbColor = baseViewHolder.getView(R.id.cb_color);
            cbColor.setText((baseViewHolder.getAdapterPosition()+1)+"");
            cbColor.setBackgroundColor(Color.parseColor(colorBean.getColorData()));
            cbColor.setChecked(isCheckList.get(baseViewHolder.getAdapterPosition()));
            isOnBind = false;
            cbColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (!isOnBind){
                        isCheckList.set(baseViewHolder.getAdapterPosition(), isChecked);
                        notifyDataSetChanged();
                    }
                }
            });
        }

        public String getSelectGroup(){
            String result = "";
            for (int i = 0; i<isCheckList.size(); i++){
                boolean isCheck = isCheckList.get(i);
                if (isCheck){
                    if (TextUtils.isEmpty(result)){
                        result = result + (i+1);
                    } else {
                        result = result + ";" + (i+1);
                    }
                    isCheckList.set(i, false);
                }
            }
            if (!TextUtils.isEmpty(result)){
                notifyDataSetChanged();
            }
            return result;
        }

    }
}
